package com.example.blmap;

import android.Manifest;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import com.example.locat.BeacoNode;
import com.example.locat.TrianBeacation;
import com.example.locat.abs.Point;

import org.altbeacon.beacon.Beacon;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BlMapActivity extends Activity {
    public static final String BEACON_ACTION = "com.example.beacondemo";
    private BlMapAdapter adapter;
    private static final int PERMISSION_REQUEST_COARSE_LOCATION = 1;
    private BlMapActivity.BeaconBroadcastReceiver beaconBroadcastReceiver;
    private TrianBeacation beacation;
    //private BeaconManager beaconManager = BeaconManager.getInstanceForApplication(MainActivity.this);
    Map<String, BeacoNode> beacMap = new HashMap();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_blmap);
        //setSupportActionBar(toolbar);

        List<Beacon> beacons = getIntent().getParcelableArrayListExtra("selectedBeacon");



        beaconBroadcastReceiver = new BlMapActivity.BeaconBroadcastReceiver();
        //Intent intent = new Intent(BlMapActivity.this, BeaconService.class);
        //startService(intent);

        //FloatingActionButton fab = findViewById(R.id.fab);
        //fab.setOnClickListener(new View.OnClickListener() {
        //   @Override
        //    public void onClick(View view) {
        //        Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
        //                .setAction("Action", null).show();
        //    }
        //});


        BlMapView blMapView = findViewById(R.id.blmapview);
        adapter = new BlMapAdapter(this);
        blMapView.setAdapter(adapter);
        beacation = new TrianBeacation();
      /*  for(Beacon bb : beacons){
            BeacoNode node = new BeacoNode.Builder()
                    .setPoint(50,50)
                    .set
        }*/
      Log.d("BlMapActivity",beacons.get(0).getBluetoothAddress());
      if(beacons == null || beacons.size() < 3){
          Toast.makeText(BlMapActivity.this,"beacon less than 3",Toast.LENGTH_SHORT).show();
          return ;
      }
      Beacon b1 = beacons.get(0);
        BeacoNode node1 = new BeacoNode.Builder()
                .setPoint(100,100)
                .setMajor(b1.getId2().toInt())
                .setMinor(b1.getId3().toInt())
                .setMacAddress(b1.getBluetoothAddress())
                .build();
        //C2:02:2E:00:00:CF
        //C2:02:2E:00:00:D0

        beacMap.put(b1.getBluetoothAddress(),node1);
        Beacon b2 = beacons.get(1);
        BeacoNode node2 = new BeacoNode.Builder()
                .setPoint(500,150)
                .setMajor(b2.getId2().toInt())
                .setMinor(b2.getId3().toInt())
                .setMacAddress(b2.getBluetoothAddress())
                .build();
        //450/2 = 225px/m
        //C2:02:2E:00:00:CF
        //C2:02:2E:00:00:D0
        //41:E8:A4:88:61:95
        //7C:4F:7C:72:AB:C5

        beacMap.put(b2.getBluetoothAddress(),node2);
        Beacon b3 = beacons.get(2);
        BeacoNode node3 = new BeacoNode.Builder()
                .setPoint(360,900)
                .setMajor(b3.getId2().toInt())
                .setMinor(b3.getId3().toInt())
                .setMacAddress(b3.getBluetoothAddress())
                .build();
        //C2:02:2E:00:00:CF
        //C2:02:2E:00:00:D0
        beacMap.put(b3.getBluetoothAddress(),node3);
        /*beacation.addNode(node1).addNode(node2).addNode(node3);

        Point location = beacation.getLocation();
        adapter.addBeacon(node1);
        adapter.addBeacon(node2);
        adapter.addBeacon(node3);
        adapter.addRevicer(new Revicer("AA","ccc",location,100));*/
       /* new AsyncTask<String, Integer, String>() {
            @Override
            protected String doInBackground(String... strings) {
                for(int i=0;i<1000;i++){
                    adapter.clearBeacon();
                    adapter.clearRevicer();
                    Beacon beacon = new Beacon(new Point(new Random().nextInt(1000)+100,new Random().nextInt(1000)+200),new Random().nextInt(1000),"zzz", UUID.randomUUID().toString(),"1abc-1123123ac-123a-879c");

                    Revicer revicer = new Revicer("xxx","1231-aacd-1235-7457",new Point(new Random().nextInt(1000)+100,new Random().nextInt(1000)+200),new Random().nextInt(1000));
                    adapter.addBeacon(beacon);
                    adapter.addRevicer(revicer);
                   // adapter.addRevicer(new Point(i*20,i*15),400);
                    //adapter.addRevicer(new Point(300,300),200);
                    adapter.notifyDataSetChanged();
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                return null;
            }
        }.execute();*/




    }

    private void init() {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
       // if(beaconBroadcastReceiver != null){
        //    unregisterReceiver(beaconBroadcastReceiver);
      //  }
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(beaconBroadcastReceiver,getBeaconIntentFilter());
    }

    @Override
    protected void onPause() {
        super.onPause();
        if(beaconBroadcastReceiver != null){
            unregisterReceiver(beaconBroadcastReceiver);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        adapter.clearBeacon();
        adapter.clearRevicer();
        //adapter.addCircle(new Point(600,750),250);

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {

            adapter.notifyDataSetChanged();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    class BeaconBroadcastReceiver extends BroadcastReceiver {


        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BEACON_ACTION.equals(action)) {
                List<Beacon> beacons = intent.getParcelableArrayListExtra("beacon");
                for(org.altbeacon.beacon.Beacon beacon : beacons){
                    String macAddress = beacon.getBluetoothAddress();
                    if(beacMap.containsKey(macAddress)){

                        BeacoNode beacoNode = beacMap.get(macAddress);

                        beacoNode.setDistence(beacon.getDistance()*225);
                        Log.d("toUUID ",beacon.getId1().toUuid().toString());
                        beacoNode.setUUID(beacon.getId1().toUuid().toString());
                        beacoNode.setRssi(beacon.getRssi());
                        beacMap.put(macAddress,beacoNode);
                        continue;
                    }
                    Toast.makeText(BlMapActivity.this,"unknow Beacon : "+macAddress,Toast.LENGTH_SHORT);
                }

                if(beacMap.size() >= 3){
                    beacation.removeAll();
                    adapter.clearBeacon();
                    adapter.clearRevicer();
                    for(BeacoNode node : beacMap.values()){
                        Log.d("NODE",node.getPoint().getX()+", "+node.getPoint().getY());
                        //  if(node.getDistence() > 0) {
                        Log.d("node.getDistence() : ",node.getPoint().toString()+""+node.getDistence());
                        beacation.addNode(node);
                        adapter.addBeacon(node);
                        //    }
                    }
                    Point location = beacation.getLocation();
                    if(location == null){
                        Log.d("BeacMap-size NULL: ",""+beacMap.size());
                        return ;
                    }
                    Log.d("Location",location.getX()+", "+location.getY());
                    adapter.addRevicer(new Revicer("Hello","1a",location,100));
                    adapter.notifyDataSetChanged();
                }

                Log.d("BeacMap-size: ",""+beacMap.size());
            }
        }
    }
    IntentFilter getBeaconIntentFilter() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BEACON_ACTION);
        return intentFilter;
    }
}
